package com.example.control;

import com.example.domain.t_user;
import com.example.service.AsyncService;
import com.example.service.ICommentService;
import com.example.service.IUserService;
import com.example.utils.MailUtils;
import com.example.utils.myUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.Random;

@Controller

public class AdminSettingController {
    private static final Logger logger= (Logger) LoggerFactory.getLogger(CommentControl.class);

    //异步线程
    @Autowired
    private AsyncService asyncService;

    @Autowired
    private ICommentService icomm;

    @Autowired
    private IUserService iuse;
    //邮箱
    @Autowired
    private MailUtils mailUtils;

    @RequestMapping({"/admin/settings","/admin/setting"})
    public String getSet(){
        return "back/settings";
    }
    //修改个人信息
    @PostMapping("/admin/setting/setMessage")
    public String setMessage(HttpServletRequest request,String username,String title,String describes){

        HttpSession session = request.getSession();
        t_user loginUser = (t_user) session.getAttribute("loginUser");
        t_user select = iuse.Select(username);
        if(select!=null&&select.getId()!=loginUser.getId()){
            request.setAttribute("res","用户名已存在");
            return "back/settings";
        }
        if(username!=null&&!username.equals("")) {
            icomm.setAuther(loginUser.getUsername(),username);
            loginUser.setUsername(username);
        }
        if(title!=null&&!title.equals(""))loginUser.setTitle(title);
        if(describes!=null&&!describes.equals(""))loginUser.setDescribes(describes);

        iuse.update(loginUser);
        session.setAttribute("loginUser",loginUser);
        logger.info(loginUser.getUsername()+" 修改信息成功");
        return "back/settings";
    }
    //修改密码
    @PostMapping("/admin/setting/setPassword")
    public String setPass(HttpServletRequest request,String oldPassword2,String newPassword2){
        //密码编码
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

        HttpSession session = request.getSession();
        t_user loginUser = (t_user) session.getAttribute("loginUser");
        if(loginUser==null){
            request.setAttribute("res","未登录");return "back/settings";
        }
        if(!encoder.matches(oldPassword2,loginUser.getPassword())){
            request.setAttribute("res","用户输入密码错误");return "back/settings";
        }
        //更新密码
        String encode = encoder.encode(newPassword2);
        loginUser.setPassword(encode);
        //修改数据库
        iuse.update(loginUser);

        session.setAttribute("loginUser",loginUser);

        logger.info(loginUser.getUsername()+" 成功修改密码");
        request.setAttribute("res","修改成功");
        return "back/settings";
    }
    //使用邮箱验证码修改密码
    @PostMapping("/admin/setting/setPasswordByEmail")
    public String checkPass(HttpServletRequest request,String code3,String newPassword3){

        //密码编码
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(newPassword3);

        HttpSession session = request.getSession();
        String userCode = (String) session.getAttribute("userCode");
        Long userCode_time = (Long) session.getAttribute("userCode_time");
        //判断验证码的合理性
        if(userCode==null||!userCode.equals(code3)){
            request.setAttribute("res","验证码错误");
            return "back/settings";
        }

        if(new Date().getTime()-userCode_time>1000*60*3){
            request.setAttribute("res","验证码超时");
            return "back/settings";
        }
        //修改密码
        t_user loginUser = (t_user) session.getAttribute("loginUser");
        loginUser.setPassword(encode);

        //更新用户信息
        session.setAttribute("loginUser",loginUser);


        //修改数据库
        if(iuse.update(loginUser)){
            request.setAttribute("res","修改成功");
            logger.info(loginUser.getUsername()+"成功通过邮箱修改密码");
        }else{
            session.setAttribute("loginUser",null);
            request.setAttribute("res","修改失败,异常退出");
        }
        return "back/settings";

    }

    //获取验证码
    @RequestMapping(value = "/admin/setting/sendCode")
    @ResponseBody
    public Boolean getCode(HttpServletRequest request){
        try{
            t_user loginUser = (t_user) request.getSession().getAttribute("loginUser");

            if(loginUser==null){
                return false;
            }
            String code = getRandomNum(6);
            //验证码放入session
            request.getSession().setAttribute("userCode", code);
            //设置验证码的时间
            request.getSession().setAttribute("userCode_time", new Date().getTime());



            try{
                asyncService.asyncInvoke(()->{
                    //System.out.println("begin");
                    mailUtils.sendMail(loginUser.getEmail(),
                            "CrazyStone个人博客小站提示你：即将修改登录，本次验证码：" + code + ",有效时间三分钟",
                            "CrazyStone个人博客小站");
                    //System.out.println("sucess");
                });
            }catch(Exception e){
                logger.error("异步线程发送邮箱失败，错误信息："+e.getMessage());
            }

            //System.out.println(true);
            return true;



        }catch (Exception e){
            logger.error("发送验证码失败，错误信息:"+e.getMessage());
            return false;
        }
    }
    private String getRandomNum(int i) {
        Random random = new Random();
        String res="";
        while(i-->0){
            res+=String.valueOf(random.nextInt(10));
        }
        return res;
    }
    //校验验证码
    @RequestMapping({"/admin/setting/checkCode"})
    public String checkCode(HttpServletRequest request,
                            @RequestParam String email,@RequestParam String code ){

        HttpSession session = request.getSession();
        String userCode = (String) session.getAttribute("userCode");
        Long userCode_time = (Long) session.getAttribute("userCode_time");
        if(userCode==null||!userCode.equals(code)){
            request.setAttribute("res","验证码错误");
            return "back/settings";

        }

        if(new Date().getTime()-userCode_time>1000*60*3){
            request.setAttribute("res","验证码超时");
            return "back/settings";
        }
        if(iuse.SelectEmail(email)!=null){
            request.setAttribute("res","该邮箱已被注册");
            return "back/settings";
        }
        t_user loginUser = (t_user) session.getAttribute("loginUser");
        loginUser.setEmail(email);
        //更新用户信息
        session.setAttribute("loginUser",loginUser);

        try{
            asyncService.asyncInvoke(()->{
                mailUtils.sendMail(email,
                        "CrazyStone个人博客小站提示你：修改绑定邮箱成功",
                        "CrazyStone个人博客小站");
            });
        }catch(Exception e){
            logger.error("异步线程发送邮箱失败，错误信息："+e.getMessage());
        }

        if(iuse.update(loginUser)){
            request.setAttribute("res","修改成功");
            logger.info(loginUser.getUsername()+"用户成功修改绑定邮箱");
        }else{
            request.setAttribute("res","修改失败");
        }
        return "back/settings";

    }

    //上传头像文件处理
    @RequestMapping("/admin/setting/addAvatar")
    public String tpUploadFile(MultipartFile avatar, HttpServletRequest request){
        HttpSession session = request.getSession();

        t_user loginUser = (t_user) session.getAttribute("loginUser");

        //图片大小不能高于5kb
        //System.out.println(avatar.getSize());
        if(avatar.getSize()>1024*500){
            //request.setAttribute("msg","图片大小不能超过500KB");
            logger.warn("文件上传大小超限："+avatar.getSize());
            return "redirect:/admin";
        }
        String imageBinary = null;
        try {
            //将图片转为二进制流
            imageBinary = myUtils.getImageBinary(avatar);
        } catch (IOException e) {
            logger.error("文件上传读取失败，错误信息："+e.getMessage());
            //request.setAttribute("msg","头像文件读取失败，请检查图片格式");
            return "redirect:/admin";
        }
        //更新用户
        iuse.updateAvatar(imageBinary,loginUser.getId());
        loginUser.setAvatar(imageBinary);
        session.setAttribute("loginUser",loginUser);
        logger.info("头像文件上传成功："+avatar.getOriginalFilename()+",size:"+avatar.getSize());


        //request.setAttribute("msg","头像修改成功");
        return "redirect:/admin";
    }
    //获取头像信息
    @RequestMapping("/admin/user/image")
    public void getUserImage(HttpSession session, HttpServletResponse response){
        t_user loginUser = (t_user) session.getAttribute("loginUser");
        if(loginUser.getAvatar()==null||"".equals(loginUser.getAvatar()))return ;
        try {
            BufferedImage bufferedImage = myUtils.base64StringToImage(loginUser.getAvatar());

            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(bufferedImage,"jpg",outputStream);
        } catch (IOException e) {
            logger.error("用户获取头像失败，错误信息："+e.getMessage());
        }
    }
}
